package solution._0020._0022;

import java.util.*;

/**
 * Created by chen_snow
 * Date: 2021/5/13 23:58
 * Description:
 */
public class Solution {

    private LinkedList<String> result = new LinkedList<>();
    private ArrayList<Character> quotes = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        quotes.add('(');
        quotes.add(')');

        StringBuffer stringBuffer = new StringBuffer();

        generateQuote(0, 2 * n, result, 0, stringBuffer);
        return result;
    }

    public void generateQuote(int currentIndex, int allIndex, LinkedList<String> result, int num, StringBuffer stringBuffer) {

        if (num < 0 || currentIndex > allIndex) {
            return;
        }

        if (currentIndex == allIndex && num == 0) {
            result.add(stringBuffer.toString());
            return;
        }

        for (int i = 0; i < 2; i++) {
            stringBuffer.append(quotes.get(i));

            if (i == 0) {
                num++;
            } else {
                num--;
            }
            generateQuote(currentIndex + 1, allIndex, result, num, stringBuffer);

            if (i == 0) {
                num--;
            } else {
                num++;
            }

            stringBuffer.deleteCharAt(stringBuffer.length() - 1);

        }
    }
}
